package com.fart.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/* 全局异常处理器 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {
    /* 异常的方式 */
    //捕获具体的异常类型
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //log.info(ex.getMessage());
        //Duplicate entry 'enron' for key 'employee.idx_username'
        if (ex.getMessage().contains("Duplicate entry ")){
            String[] ss = ex.getMessage().split(" ");
            String msg =  ss[2] + "已经存在";
            return R.error(msg);
        }
        return R.error("未知异常");
    }
    //系统异常

    //业务异常
    @ExceptionHandler(BusinessException.class)
    public R<String> exceptionBusiness(BusinessException ex){
        log.info(ex.getMessage());

        return R.error(ex.getMessage());
    }
    //其他异常
}
